const current = 'v1'

self.addEventListener('install', function(event) {
  self.skipWaiting();

  event.waitUntil(
    caches.open(current).then(function(cache) {
      return cache.addAll([
        '/index.html',
        '/index.min.js',
        '/img.html',
        '/18023.jpg'
      ]);
    })
  );
});

self.addEventListener('activate', function(event) {
  const cacheWhitelist = [current];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

self.addEventListener('fetch', function(event) {
  if (event.request.url.includes('http://localhost:8081')) {
    event.respondWith(
      caches.match(event.request).then(function() {
        return fetch(event.request).then(function(response) {
          return caches.open(current).then(function(cache) {
            cache.put(event.request, response.clone());
            return response;
          });
        });
      }).catch(function() {
        return caches.match('/18023.jpg');
      })
    );
  }
});